from rest_framework_jwt.settings import api_settings
from rest_framework import serializers
from md_shop.models import UresReg
# from userapp.models import User


class UserSerializer(serializers.Serializer):
    id  =serializers.IntegerField(read_only=True)
    username = serializers.CharField()
    password = serializers.CharField()
    phone = serializers.CharField()
    email = serializers.CharField()
    token = serializers.CharField(read_only=True)

    def create(self, data):
        user = User.objects.create(**data)
        #数据库里密码的加密（固定的步骤）
        user.set_password(data.get('password'))
        user.save()

        # 补充生成记录登录状态的token  固定的格式，用过来生成jwt的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        #把token发放在user里返回
        user.token = token
        return user

class UserSer(serializers.ModelSerializer):
    class Meta:
        modul = UresReg
        fields = '__all__'
